package com.xm.queue.task2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 任务消费者（工人）
 */
@Slf4j
public class TaskWorker implements Runnable {
    private final TaskManager taskManager;
    private final int no;
    public TaskWorker(TaskManager taskManager, int no) {
        this.taskManager = taskManager;
        this.no = no;
    }
    public static volatile AtomicInteger count = new AtomicInteger(0);

    @Override
    public void run() {
        log.info("工人[{}]已上线，正在加班加点工作。。", no);
        ITask task;
        while (!Thread.currentThread().isInterrupted()) {
            try {
                task = this.taskManager.getTask();
//                task = this.taskManager.getTask2);
                if (task != null) {
                    processTask(task);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    /**
     * 任务处理逻辑
     * @param task 继承 BaseTask 基础任务模板的任务
     */
    private void processTask(ITask task) {
        try {
            task.run();
            count.incrementAndGet();
        } catch (Exception e) {
            handleTaskFailure(task, e.getMessage());
        }
    }

    /**
     * 失败处理（含重试逻辑）
     * @param task 继承 BaseTask 基础任务模板的任务
     * @param reason 失败原因
     */
    private void handleTaskFailure(ITask task, String reason) {
        if (task.getRetryCount() < 3) {
            task.incrementRetryCount();

            // 延迟重试（使用独立线程池）TODO
        } else {
            // 放入私信队列
            // 添加日志（加入数据库）
            log.error("task finally failed：{}", reason);
        }
    }
}
